﻿using MLSMooc.BO;
using MLSMooc.Service.Interface.Course;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MLSMooc.Helper;
using System.Data.SqlClient;
using Dapper;

namespace MLSMooc.Service.Implement.Course
{
   public class CourseServiceImpl :ICourseServiceImpl
    {
        private static CourseServiceImpl instance = new CourseServiceImpl();
        private CourseServiceImpl() { }
        public static CourseServiceImpl Getinstance() => instance;

        public async Task<int> InsertCourseBrowseInfo(BrowseBO data)
        {
            using (SqlConnection conn=new SqlConnection(SalesSysSqlHelper.connectionString))
            {
                StringBuilder sql = new StringBuilder();
                sql.Append($@"insert into  Mooc_CourseBrowseInfo values(@AdminId,@ResourceId,@StartTime,@EndTime,'',getdate(),getdate(),0)");
                var res = await conn.ExecuteAsync(sql.ToString(), new { AdminId = data.AdminId, ResourceId = data.ResourceId, StartTime = data.StartTime, EndTime = data.EndTime });
                if (res>0)
                {
                   await UpMenuBrowseCount(data.ResourceId);
                    var res1 = await UpCourseBrowseCount(data.ResourceId);
                    return res1;
                }
                else
                {
                    return 0;
                }
            }
        }

        public async Task<int> UpMenuBrowseCount(int id)
        {
            using (SqlConnection conn=new SqlConnection(SalesSysSqlHelper.connectionString))
            {
                StringBuilder sql = new StringBuilder();
                sql.Append($@"update Mooc_Resource_Menu set BrowseCount=BrowseCount+1 where Type=2 and ResourceId=@id");
                var res = await conn.ExecuteAsync(sql.ToString(), new { id = id });
                return res;
            }
        }

        public async Task<int> UpCourseBrowseCount(int id)
        {
            using (SqlConnection conn = new SqlConnection(SalesSysSqlHelper.connectionString))
            {
                StringBuilder sql = new StringBuilder();
                sql.Append($@"update Mooc_Course set Course_BrowseNumber=Course_BrowseNumber+1 where Id=@id");
                var res = await conn.ExecuteAsync(sql.ToString(), new { id = id });
                return res;
            }
        }
    }
}
